﻿using SAP.Middleware.Connector;
using Sie.eMES.ThinClient.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
   public class Class1
    {
       SapPersistBroker sapProvider;
       public Class1()
       {
           sapProvider = new SapPersistBroker();
       }


        public  string UpLoadSAP(DataTable dt, string p_user_code)
        {

            RfcDestination rd = this.sapProvider.GetRfcDes();
            RfcRepository rfcrep = rd.Repository;
            IRfcFunction myfun = null;
            myfun = rfcrep.CreateFunction("ZZERP_MES_STRUCTURE_TRANS_026");
            myfun.Invoke(rd);
            IRfcTable tH = myfun.GetTable("IT_TABLE");
            tH = ConvertDataTableToRFCTable(dt, tH, rfcrep);
            myfun = rfcrep.CreateFunction("ZZERP_MES_026");
            myfun.SetValue("IM_DATA", tH);
            myfun.SetValue("IM_USERNAME", p_user_code);
            myfun.Invoke(rd);
            IRfcTable dataLog = myfun.GetTable("EX_DATA_LOG");
            string message = myfun.GetString("EX_MESSAGE");

            return message;

        }
        public IRfcTable ConvertDataTableToRFCTable(DataTable dt, IRfcTable rfcT, RfcRepository rr)
        {
            if (dt.Rows.Count != 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    IRfcStructure import = rr.GetStructureMetadata("ZZSMES026").CreateStructure();
                    import.SetValue("EBELN", dr["PONUMBER"].ToString());
                    import.SetValue("EBELP", dr["poline"].ToString());
                    import.SetValue("SOBKZ", dr["SOBKZ"].ToString());
                    import.SetValue("MATNR", dr["itemcode"].ToString());
                    import.SetValue("WERKS", dr["ORGID"].ToString());
                    import.SetValue("MENGE", dr["quantity"].ToString());
                    import.SetValue("ZWSHL", dr["ZWSHL"].ToString());
                    import.SetValue("ZBCSH", dr["AlrQty"].ToString());
                    import.SetValue("MEINS", dr["UNIT"].ToString());
                    import.SetValue("BATCH", dr["barcode"].ToString());
                    import.SetValue("LGORT", dr["STORAGELOCATION"].ToString());
                    import.SetValue("PSTYP", dr["pstyp"].ToString());
                    import.SetValue("ZSCRQ", dr["outdate"].ToString());
                    import.SetValue("LIFNR", dr["vendorcode"].ToString());
                    import.SetValue("KNTTP", dr["KNTTP"].ToString());
                    import.SetValue("VBELN", dr["vbeln"].ToString());
                    import.SetValue("VBELP", dr["batchcode"].ToString());
                    //rfcT.Insert(rfcS); 
                    rfcT.Append(import);
                }

            }
            return rfcT;
        }          
    }
}
